import matplotlib.pyplot as plt
import numpy as np

# 设置中文字体、字号等
plt.rcParams['font.sans-serif'] = ['STZhongsong']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.size'] = 14
# 2000 - 2020 年，每五年一个数据点
years = [2000, 2005, 2010, 2015, 2020]
# 模拟呼包鄂三市常住人口数据（单位：万人）
hohhot_pop = [210.0, 240.0, 280.0, 320.0, 363.94]
baotou_pop = [210.0, 235.0, 260.0, 275.0, 277.21]
ordos_pop = [130.0, 160.0, 190.0, 210.0, 224.05]
x = np.arange(len(years))  # 年份的位置
width = 0.25  # 柱子宽度
fig, ax = plt.subplots(figsize=(10, 6))
# 绘制三组柱状图
rects1 = ax.bar(x - width, hohhot_pop, width,
                label='呼和浩特市')
rects2 = ax.bar(x, baotou_pop, width, label='包头市')
rects3 = ax.bar(x + width, ordos_pop, width,
                label='鄂尔多斯市')


# 添加柱子上的标签函数
def add_labels(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate(f'{height:.2f}',
                    xy=(rect.get_x() + rect.get_width() / 2,
                        height),
                    xytext=(0, -10),
                    textcoords="offset points",
                    ha='center', va='top',
                    fontsize=14,
                    weight='bold',
                    color='white',
                    rotation=90)


# 分别添加标签
add_labels(rects1)
add_labels(rects2)
add_labels(rects3)
# 设置图表样式
ax.set_ylabel('人口数 (万人)')
ax.set_xlabel('年度')
ax.set_title('呼包鄂三市2000-2020年每五年常住人口变化')
ax.set_ylim(0, 400)  # 根据新数据调整Y轴范围
ax.set_xticks(x)
ax.set_xticklabels(years)
ax.legend(loc='upper left')
fig.tight_layout()
plt.savefig("./Figures/bar10-3.png", dpi=300)
plt.show()
